//
//  ContactListViewController.swift
//  Contacts
//
//  Created by 李文深 on 16/8/11.
//  Copyright © 2016年 30pay. All rights reserved.
//  https://developer.apple.com/library/ios/samplecode/TableMultiSelect/Introduction/Intro.html

import UIKit
import RealmSwift

class ContactListViewController: UITableViewController {
    
    let realm = try! Realm()
    let dataArray = try! Realm().objects(Contact.self)
    var notificationToken: NotificationToken?
    
    @IBOutlet var editButton: UIBarButtonItem!
    @IBOutlet var cancelButton: UIBarButtonItem!
    @IBOutlet var deleteButton: UIBarButtonItem!
    @IBOutlet var addButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "联系人"
        
        tableView.allowsMultipleSelectionDuringEditing = true
        
        updateButtonsToMatchTableState()
        
        // Set results notification block
        self.notificationToken = dataArray.addNotificationBlock {[weak self] (changes: RealmCollectionChange) in
            
            guard let tableView = self?.tableView else {
                return
            }
            
            switch changes {
            case .Initial:
                // Results are now populated and can be accessed without blocking the UI
                tableView.reloadData()
                break
            case .Update(_, let deletions, let insertions, let modifications):
                // Query results have changed, so apply them to the TableView
                tableView.beginUpdates()
                tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) },
                    withRowAnimation: .Automatic)
                tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) },
                    withRowAnimation: .Automatic)
                tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) },
                    withRowAnimation: .Automatic)
                tableView.endUpdates()
                break
            case .Error(let err):
                // An error occurred while opening the Realm file on the background worker thread
                fatalError("\(err)")
                break
            }
            
            self?.updateButtonsToMatchTableState()
        }
    }
    
    private func updateButtonsToMatchTableState() {
        if tableView.editing {
            
            // Show the option to cancel the edit.
            navigationItem.rightBarButtonItem = cancelButton
            
            updateDeleteButtonTitle()
            
            // Show the delete button.
            navigationItem.leftBarButtonItem = deleteButton
        } else {
            // Not in editing mode.
            navigationItem.leftBarButtonItem = addButton
            
            // Show the edit button, but disable the edit button if there's nothing to edit.
            if (dataArray.count > 0) {
                editButton.enabled = true
            }else{
                editButton.enabled = false
            }
            navigationItem.rightBarButtonItem = editButton
        }
    }
    
    private func updateDeleteButtonTitle() {
        
        if let selectedRows = tableView.indexPathsForSelectedRows where selectedRows.count != dataArray.count {
            deleteButton.title = "Delete (\(selectedRows.count))" //有选中的行但用户没有全选
        }
        else {
            deleteButton.title = "Delete All"
        }
    }
    
    
    //MARK: - Unwind Segue Methods
    @IBAction func addContact(segue: UIStoryboardSegue) {
        
        let sourceVC = segue.sourceViewController as! AddContactViewController
        
        let avatarImage = sourceVC.avatarImageView.image
        let name        = sourceVC.nameField.text
        let phoneNumber = sourceVC.phoneNumberField.text
        let contact     = Contact()
        contact.avatar = UIImageJPEGRepresentation(avatarImage!, 1.0)
        contact.name = name!
        contact.phoneNumber = phoneNumber!
        
        realm.beginWrite()
        realm.add(contact)
        try! realm.commitWrite()
    }
    
    
    @IBAction func saveContact(segue: UIStoryboardSegue) {
        
        let sourceVC = segue.sourceViewController as! EditContactViewController
        
        let avatarImage = sourceVC.avatarImageView.image
        let name        = sourceVC.nameField.text
        let phoneNumber = sourceVC.phoneNumberField.text
        
        let indexPath = sourceVC.editingIndexPath
        
       try! realm.write {
            let contact = dataArray[indexPath.row]
            contact.avatar = UIImageJPEGRepresentation(avatarImage!, 1.0)
            contact.name = name!
            contact.phoneNumber = phoneNumber!
        }
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if segue.identifier == "EditContactViewController" {
            let cell = sender as! ContactViewCell
            let indexPath = tableView.indexPathForCell(cell)
            let vc = segue.destinationViewController as! EditContactViewController
            vc.contact = dataArray[indexPath!.row]
            vc.editingIndexPath = indexPath
        }
    }
    
    override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
        return !tableView.editing //tableView正在编辑的时候禁止跳转
    }
    
}

// MARK: - Table view data source
extension ContactListViewController {
    
    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as! ContactViewCell
        
        let contact = dataArray[indexPath.row]
        
        cell.configCell(contact)
        
        return cell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if !tableView.editing {  //当tableView不是在选中状态时候,取消其选中样式
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
        }
        updateButtonsToMatchTableState()
    }
    
    override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        updateDeleteButtonTitle()
    }
    
    override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        return .Delete
    }
    
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
        switch editingStyle {
        case .Delete:
            realm.beginWrite()
            realm.delete(dataArray[indexPath.row])
            try! realm.commitWrite()
        case .Insert,.None:
            break
        }
    }
}

//MARK:actions
extension ContactListViewController {
    
    @IBAction func editAction(sender: UIBarButtonItem) {
        tableView.setEditing(false, animated: true) //适配在删除编辑状态下出现的UI的bug
        tableView.setEditing(true, animated: true)
        updateButtonsToMatchTableState()
    }
    
    @IBAction func cancelAction(sender: UIBarButtonItem) {
        tableView.setEditing(false, animated: true)
        updateButtonsToMatchTableState()
    }
    
    @IBAction func deleteAction(sender: UIBarButtonItem) {
        
        let alertVC =  UIAlertController(title: "tip", message: "Are you sure to delete", preferredStyle: .ActionSheet)
        let confirmAction = UIAlertAction(title: "Delete", style: .Destructive, handler: { _ in
            
            let realm = try! Realm()
            
           if let selectedRows = self.tableView.indexPathsForSelectedRows { //删除部分
            
                realm.beginWrite()
                for selectionIndex in selectedRows {
                    realm.delete(self.dataArray[selectionIndex.row])
                }
                try! realm.commitWrite()
            
           } else { //删除全部
              realm.beginWrite()
              realm.deleteAll()
              try! realm.commitWrite()
            }
            
            // Exit editing mode after the deletion.
            self.tableView.setEditing(false, animated: true)
        })
        alertVC.addAction(confirmAction)
        
        let cancelAction = UIAlertAction(title: "Calcel", style: .Cancel, handler: nil)
        alertVC.addAction(cancelAction)
        
        self.presentViewController(alertVC, animated: true, completion: nil)
    }
}
